package cc.teamin.cms.component;

import cc.teamin.core.properties.TeaminProperties;
import cc.teamin.core.response.Response;
import cc.teamin.core.utils.HttpClientUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 微信组件类
 *
 * 获取accessToken
 *
 * 群发消息
 *
 * Created by e on 2017/12/7
 *
 * @author <a href="http://eregg.com">eregg</a>
 */
@Component
public class WeixinComponent {

    private static Logger logger = LoggerFactory.getLogger(WeixinComponent.class);

    private static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private static final String URL_SEND_MESSAGE_ALL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=%s";
    //17:05:08.221 [main] INFO cc.teamin.core.utils.HttpClientUtil - response:{"access_token":"pEYMlZ-4Q7ckQubCQ1aSj3_THpRDdZcj2mSIfZRgZAlzd-MPy2ribVpKx_iMrl1MW0xtMug0ul22ZhLJBQOgUNM5107Zj2aNfRZGpRokTN0YBXbAFAPSO","expires_in":7200}

    private static String accessToken = "niEjKhC_P9zXenWXxaHD_H9OIj9khMa4vNAu67DCAQAb9-0o5IYI2AGj40Tq9-qct37VkyFtOHKAeEHsbOVVyAtSQJ51HJvvl-XK5UVc4yse8VfXTcd8qHIMhKfkRTYTLWFgAIATEN";
    @Autowired
    private TeaminProperties teaminProperties;

    /**
     * 获取accessToken
     *
     * 建议公众号开发者使用中控服务器统一获取和刷新Access_token，
     * 其他业务逻辑服务器所使用的access_token均来自于该中控服务器，
     * 不应该各自去刷新，否则容易造成冲突，导致access_token覆盖而影响业务；
     * @return
     */
    public String getAccessToken(){

        String url = String.format(URL_ACCESS_TOKEN, teaminProperties.getWx().getAppId(), teaminProperties.getWx().getSecret());

        logger.info("request:{}", url);
        String result = HttpClientUtil.doGet(url);
        logger.info("response:{}", result);

        return null;
    }

    /**
     * 群发消息
     * doc https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21
     * @param messageJson
     * @return
     */
    public Response sendMessageToAll(String messageJson){

        String url = String.format(URL_SEND_MESSAGE_ALL, accessToken);

        /*
        {
           "filter":{
              "is_to_all":true
           },
           "text":{
              "content":"CONTENT"
           },
            "msgtype":"text"
        }
         */


        Map<String, Object> filterMap = new HashMap<>();
        //用于设定是否向全部用户发送，值为true或false，选择true该消息群发给所有用户，选择false可根据tag_id发送给指定群组的用户
        filterMap.put("is_to_all", true);

        Map<String, String> textMap = new HashMap<>();
        textMap.put("content", messageJson);

        JSONObject jsonObject = new JSONObject();
        //用于设定图文消息的接收者
        jsonObject.put("filter", filterMap);
        jsonObject.put("text", textMap);
        //群发的消息类型，图文消息为mpnews，文本消息为text，语音为voice，音乐为music，图片为image，视频为video，卡券为wxcard
        jsonObject.put("msgtype", "text");

        logger.info("request: url:{}, json:{}", url, jsonObject.toString());
        String result = HttpClientUtil.doPostJson(url, jsonObject.toString());
        logger.info("response:{}", result);

        return null;
    }


}
